<template>
  <scroll class="suggest" ref="suggest" :data="result" :pullup="pullup"
          :beforeScroll="beforeScroll"
          @beforeScroll="listScroll"
          @scrollToEnd="pullUpRefresh">
    <ul class="suggest-list">
      <li class="suggest-item"  v-for="item in result" @click="selectItem(item)">
        <div class="icon">
          <i :class="getIconType(item)"></i>
        </div>
        <div class="name">
          <p class="text" v-html="getDisplayName(item)"></p>
        </div>
      </li>
      <li><loading v-show="hasMore" title=""> </loading></li>
    </ul>
    <div class="no-result-wrapper" v-show="!hasMore && !result.length">
      <no-result :title="`抱歉!没有搜索到结果`"> </no-result>
    </div>
  </scroll>
</template>
<script type="text/ecmascript-6">
  import Scroll from 'base/scroll/scroll'
  import Loading from 'base/loading/loading'
  import NoResult from 'base/noresult/noresult'
  import {search} from 'api/search'
  import {ERR_OK} from 'api/config'
  import {createSong} from 'common/js/song'
  import Singer from 'common/js/singer'
  import {mapMutations, mapActions} from 'vuex'

  const PERPAGE = 20
  const TYPE_SINGER = 'singer'
  export default{
    name: 'SearchSuggest',
    data() {
      return {
        page: 1,
        result: [],
        pullup: true,
        hasMore: true,
        beforeScroll: true
      }
    },
    props: {
      query: {
        type: String,
        default: ''
      },
      showSinger: {
        type: Boolean,
        default: true
      }
    },
    watch: {
      query(newVal) {
        this._search(newVal)
      }
    },
    methods: {
      _search(query) {
        // 上来刷新,,,优化每次input操作change都会引发请求，浪费资源
        this.hasMore = true
        this.page = 1
        this.$refs.suggest.scrollTo(0, 0)
        search(this.query, this.page, this.showSinger, PERPAGE).then((res) => {
          if (res.code === ERR_OK) {
            this.result = this._normalizeResult(res.data)
            this._checkMore(res.data)
            // console.log(this.result)
          }
        })
      },
      _checkMore(data) {
        const song = data.song
        if (!song.list.length || (song.curnum + song.curpage * PERPAGE) > song.totalnum){
          this.hasMore = false
        }
      },
      _normalizeResult(list) {
        let ret = []
        // zhida表示的歌手直达链接，将会存储歌手数据,对象结构解析；type是为了区分类型
        if (list.zhida && list.zhida.singermid) {
          ret.push({...list.zhida, ...{type: TYPE_SINGER}})
        }
        if (list.song) {
          ret = ret.concat(this._normalizeSongs(list.song.list))
        }
        return ret
      },
      // 为了不讲歌手处理函数这个私有函数filterSinger暴露出来，我们对拿到的结果进行处理
      _normalizeSongs(list) {
        let ret = []
        list.forEach((musicData) => {
          if (musicData.songid && musicData.albumid) {
            ret.push(createSong(musicData))
          }
        })
        return ret
      },
      getIconType(item) {
        return item.type === TYPE_SINGER ? 'icon-mine' : 'icon-music'
      },
      getDisplayName(item) {
        if (item.type === TYPE_SINGER) {
          return item.singername
        } else {
          return `${item.name}-${item.singer}`
        }
      },
      pullUpRefresh() {
        if (!this.hasMore) {
          return
        }
        this.page++
        search(this.query, this.page, this.showSinger, PERPAGE).then((res) => {
          if (res.code === ERR_OK) {
            this.result = this.result.concat(this._normalizeResult(res.data))
            this._checkMore(res.data)
          }
        })
      },
      selectItem(item) {
        if (item.type === TYPE_SINGER) {
          const singer = new Singer({
            id: item.singerid,
            mid: item.singermid,
            name: item.singername
          })
          console.log('-----search-suggest 130------', `/search/${singer.id}`)
          this.$router.push({
            path: `/search/${singer.id}`
          })
          this.setSinger(singer)
        } else {
          this.insertSong(item)
        }
        // 派出事件，以及选中歌曲，搜索，搜索历史这个功能并不是搜索结果该做的工作，为了业务组件功能明确，
        // 将该功能派发给其他组件操作,保存历史等给父组件处理
        this.$emit('select')
      },
      listScroll() {
        this.$emit('listScroll')
      },
      refresh() {
        this.$refs.suggest.refresh()
      },
      ...mapMutations({
        setSinger: 'SET_SINGER'
      }),
      ...mapActions([
        'insertSong'
      ])
    },
    components: {
      Scroll,
      Loading,
      NoResult
    }
  }
</script>
<style scoped lang="stylus" rel="stylesheet/stylus">
  @import "~common/stylus/variable"
  @import "~common/stylus/mixin"

  .suggest
    height: 100%
    overflow: hidden
    .suggest-list
      padding: 0 30px
      .suggest-item
        display: flex
        align-items: center
        padding-bottom: 20px
      .icon
        flex: 0 0 30px
        width: 30px
        [class^="icon-"]
          font-size: 14px
          color: $color-text-d
      .name
        flex: 1
        font-size: $font-size-medium
        color: $color-text-d
        overflow: hidden
        line-height 1.2
        .text
          no-wrap()
    .no-result-wrapper
      position: absolute
      width: 100%
      top: 50%
      transform: translateY(-50%)
</style>
